import React, { useState, useEffect } from "react";
import "./Publish.css"; // 引入 CSS 文件
import {ReactComponent as Target} from "../assets/icons/target.svg"; // 引入 SVG 图片
import CreateTopicModal from "./CreateTopicModal"; // 引入创建话题的弹窗组件
import { searchTopic } from '../api/userApi';
import { getMyprofile } from "../api/userApi";
import { createBlog } from "../api/userApi";
import { createInterest } from "../api/userApi";

const Publish = ({ onCancel }) => {
  const [description, setContent] = useState(""); // 发帖内容
  const [interestId, setInterestId] = useState(null); // 话题id（整数）
  const [topics, setTopics] = useState([]); // 话题名称数组
  const [image, setImage] = useState(null); // 上传的图片
  const [imageURL, setImageURL] = useState(""); // 用于显示图片的 URL
  const [suggestions, setSuggestions] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false); // 管理弹窗状态
  const [userId, setUserId] = useState(null); // 新增 userId 状态
  const [myProfile, setMyProfile] = useState(null);  // 个人信息

  useEffect(() => {
    const storedUserId = localStorage.getItem('userId');
    if (storedUserId) {
      setUserId(storedUserId);
    } 
  }, []);

  // 获取个人信息
  useEffect(() => {
    const fetchUserProfile = async () => {
      try {
        if (userId) {
          const userProfile = await getMyprofile(userId);
          if (userProfile) {
            const profile = {
              account: userProfile.account || '',
              password: userProfile.password || '',
              signature: userProfile.signature || '',
              sex: userProfile.sex || '',
              image: userProfile.image ? 'http://localhost:8080/' + userProfile.image : null,
            };
            setMyProfile(profile);
          }
        }
      } catch (error) {
        console.error('Error fetching user profile:', error);
      }
    };

    fetchUserProfile();
  }, [userId]);  // 当 userId 变化时重新请求

  // 取消按钮点击事件
  const handleCancel = () => {
    setContent("");
    // setTopics("");
    setInterestId(null);
    setTopics([]);
    setImage(null);
    setImageURL("");
    if (onCancel) {
      onCancel(); // 调用父组件的取消方法
    }
  };

  // 上传图片事件
  const handleImageUpload = (e) => {
    const file = e.target.files[0];
    if (file) {
      setImage(file);
      setImageURL(URL.createObjectURL(file)); // 生成图片的 URL
    }
  };

  // 取消上传的图片
  const handleRemoveImage = () => {
    setImage(null);
    setImageURL("");
  };
    
  // 处理输入框变化，识别 # 后面的关键词并实时搜索
  const handleTopicChange = async (e) => {
    const value = e.target.value;
    setTopics(value); // 更新输入框的内容

    // 检查是否包含 # 符号
    if (value.includes('# ')) {
      const searchTerm = value.split('# ').pop(); // 获取 # 后面的内容
      if (searchTerm.length > 0) {
        try {
          // 调用后端接口获取匹配的话题
          const result = await searchTopic(searchTerm, userId);

          // 如果返回的是数组，展示每个话题的名字
          if (Array.isArray(result)) {
            const matchedTopics = result.filter(interest => interest.name.includes(searchTerm) && searchTerm); 
            setSuggestions(matchedTopics); // 设置搜索建议
          }
        } catch (err) {
          setSuggestions([]); // 如果请求失败，清空建议列表
        }
      }
    } else {
      setSuggestions([]); // 如果没有 #，清空建议列表
    }
  };

  // 点击目标图片插入 #
  const handleTargetClick = () => {
    setTopics((prev) => [...prev, '# ']); // 将 # 插入到话题数组
    setSuggestions([]); // 点击后清空建议
  };

  // 选择建议项
  const handleSuggestionClick = (suggestion) => { 
    setInterestId(suggestion.interestId); // 假设每个话题对象都有一个 id 属性，更新 interestId
    console.log("选择话题:", suggestion.name);
    setTopics('#' + ' ' + suggestion.name); // 选中后将话题名称加入  
    setSuggestions([]); // 选中后清空建议
  };

  // 创建话题
  const handleCreateTopic = async (interest) => {
    console.log("新建话题:", interest);
    
    const { name, description, image } = interest;

    if (!name || !description) {
      alert('请填写所有必需字段！');
      return;
    }

    try {
      const result = await createInterest(userId, name, description, image);
      alert('创建话题成功！');
      console.log("新建话题结果： ",  result);
      setInterestId(result.interestId); // 更新话题 ID
      // setTopics('#' + ' ' + name); // 添加新话题名称到话题数组
      console.log("新建话题id： ",  result.interestId);
      setTopics('#' + ' ' + result.name); // 将话题名称加入
    } catch (error) {
      alert('创建话题失败，请稍后再试。'); // 处理错误
    }
  };

  
  // 发布按钮点击事件
  const handlePublish = async () => {
    if (!description.trim()) {
      alert("内容不能为空！");
      return;
    }
    if (!interestId) { //.trim()) {
      alert("话题不能为空！");
      return;
    }
    try {
      const response = await createBlog(image, interestId, userId, description);
      if (response.success) {
        alert("发布成功！");
        // 清空输入框
        setContent("");
        setInterestId(null);
        setTopics("");
        // setTopics("");
        setImage(null);
        setImageURL("");
        handleCancel();
      } else {
        alert(response.error || "发布失败，请稍后再试");
      }
    } catch (error) {
      console.error("发布帖子时出错:", error);
      alert("发布失败，请稍后再试");
    }
  };



  return (
    <div className="post-container">
      <div className="post-header">
        {/* 使用 myProfile 来显示头像 */}
        {myProfile && myProfile.image ? (
          <img className="publish-avatar" alt="头像" src={myProfile.image} />
        ) : (
          <img className="publish-avatar" alt="头像" src="http://localhost:8080/default-avatar.png" />
        )}
        <span>{myProfile ? myProfile.account : '用户'}</span>
      </div>

      <textarea
        className="post-textarea"
        placeholder="内容"
        value={description}
        onChange={(e) => setContent(e.target.value)}
      ></textarea>

    <div className="topic-container">
      <input
        className="topic-input"
        type="text"
        placeholder="添加相关话题"
        // value={interestId}
        value={topics}
        onChange={handleTopicChange}
      />
      <Target
        className="target-icon"
        onClick={handleTargetClick} // 点击图片插入#
         // 添加样式
      />
      <button className="new-topic-button" onClick={() => setIsModalOpen(true)}>
        新建话题
      </button>
      {isModalOpen && (
        <CreateTopicModal onClose={() => setIsModalOpen(false)} onCreate={handleCreateTopic} />
      )}
      {suggestions.length > 0 && (
        <ul className="suggestions-list">
          {suggestions.map((suggestion, index) => (
            <li key={index} onClick={() => handleSuggestionClick(suggestion)}>
              {/* {suggestion.interestId} */}
              {suggestion.name}
              {/* {suggestion.description} */}
              {/* {suggestion.image} */}
              {/* {suggestion.updateTime} */}
              {/* {suggestion.collectionCounts} */}
              {/* {suggestion.isCollected} */}
            </li>
          ))}
        </ul>
      )}
    </div>

      <div className="image-upload-container">
        {!image && ( // 如果没有图片则显示 label
          <label className="image-label">
            添加图片
            <input
              type="file"
              style={{ display: "none" }}
              onChange={handleImageUpload}
            />
          </label>
        )}
        {image && ( // 如果有图片则显示
          <div className="image-preview">
            <img src={imageURL} alt="Uploaded" className="uploaded-image" />
            <button className="remove-image-button" onClick={handleRemoveImage}>
              &times; {/* x号 */}
            </button>
          </div>
        )}
      </div>

      <div className="button-container">
        <button className="cancel-button" onClick={handleCancel}>
          取消
        </button>
        <button className="publish-button" onClick={handlePublish}>
          发布
        </button>
      </div>
    </div>
  );
};

export default Publish;
